import org.apache.log4j.Logger;

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * A tool that produces a log will printing to it messages from the dalet log that are XMl relaited
 */
public class OutputManager {

    public static Logger logger = Logger.getLogger(OutputManager.class);  //the logger used. configured in log4j.properties

    /**
     * recives a line from a log file and parses it to a title and a pretty-printed XML.
     * @param strLine the line from a log file
     * @param delimiter the delimiter between the title and the XML: ether "<-" or "->"
     */
    public static void logLine(String strLine, String delimiter){

        String[] line;
        String title, xml;
        //TODO: add input vertification
        //TODO: reg expression
        line = strLine.split(delimiter);
        title = line[0].concat("\n");
        xml = line[1];
        logger.debug(title);
        //String prettyXml;
        try{
            xml = PrettyPrint(xml);
        }
        catch (Exception e){
            //prettyXml = xml;
        }
        logger.debug(xml);
        logger.debug("********************************************************************");

    }

    /**
     * turns xml to pretty print
     * @param xml the plain xml text
     * @return a pretty printed xml
     * @throws Exception
     */
    public static String PrettyPrint (String xml)  {

        try {
            Source xmlInput = new StreamSource(new StringReader(xml));
            StreamResult xmlOutput = new StreamResult(new StringWriter());
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            transformer.transform(xmlInput, xmlOutput);
            xml=xmlOutput.getWriter().toString();
        }
        catch (TransformerException e) {
            // e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        //System.out.println("THE RESULT XML " + xml);
        return xml;
    }
}
